πŸ‘©β€πŸ’» 42840. λͺ¨μ˜κ³ μ‚¬

@Seongukbaek Posted April 15, 2022 Β· Updated April 15, 2022 Β· 3 min read

문제

μˆ˜ν¬μžλŠ” μˆ˜ν•™μ„ ν¬κΈ°ν•œ μ‚¬λžŒμ˜ μ€€λ§μž…λ‹ˆλ‹€. 수포자 삼인방은 λͺ¨μ˜κ³ μ‚¬μ— μˆ˜ν•™ 문제λ₯Ό μ „λΆ€ 찍으렀 ν•©λ‹ˆλ‹€. μˆ˜ν¬μžλŠ” 1번 λ¬Έμ œλΆ€ν„° λ§ˆμ§€λ§‰ λ¬Έμ œκΉŒμ§€ λ‹€μŒκ³Ό 같이 μ°μŠ΅λ‹ˆλ‹€.

1번 μˆ˜ν¬μžκ°€ μ°λŠ” 방식: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ... 2번 μˆ˜ν¬μžκ°€ μ°λŠ” 방식: 2, 1, 2, 3, 2, 4, 2, 5, 2, 1, 2, 3, 2, 4, 2, 5, ... 3번 μˆ˜ν¬μžκ°€ μ°λŠ” 방식: 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, ...

1번 λ¬Έμ œλΆ€ν„° λ§ˆμ§€λ§‰ λ¬Έμ œκΉŒμ§€μ˜ 정닡이 μˆœμ„œλŒ€λ‘œ 듀은 λ°°μ—΄ answersκ°€ μ£Όμ–΄μ‘Œμ„ λ•Œ, κ°€μž₯ λ§Žμ€ 문제λ₯Ό 맞힌 μ‚¬λžŒμ΄ λˆ„κ΅¬μΈμ§€ 배열에 λ‹΄μ•„ return ν•˜λ„λ‘ solution ν•¨μˆ˜λ₯Ό μž‘μ„±ν•΄μ£Όμ„Έμš”.

μ œν•œμ‚¬ν•­

  • μ‹œν—˜μ€ μ΅œλŒ€ 10,000 문제둜 κ΅¬μ„±λ˜μ–΄μžˆμŠ΅λ‹ˆλ‹€.
  • 문제의 정닡은 1, 2, 3, 4, 5쀑 ν•˜λ‚˜μž…λ‹ˆλ‹€.
  • κ°€μž₯ 높은 점수λ₯Ό 받은 μ‚¬λžŒμ΄ μ—¬λŸΏμΌ 경우, returnν•˜λŠ” 값을 μ˜€λ¦„μ°¨μˆœ μ •λ ¬ν•΄μ£Όμ„Έμš”.

μž…μΆœλ ₯ 예

answers return
[1,2,3,4,5] [1]
[1,3,2,4,2] [1,2,3]

πŸ“ Logic

private int countScore(int[] answers, int[] std) { int score = 0; for (int i = 0, idx = 0; i < answers.length; i++) { if (idx >= std.length) idx = idx % std.length; if (std[idx++] == answers[i]) score++; } return score; }
  • μ£Όμ–΄μ§„ ν•™μƒμ˜ μ •λ‹΅ 배열을 κ°€μ§€κ³  점수λ₯Ό λ§€κΈ΄λ‹€.
  • λ‹€λ§Œ μ£Όμ–΄μ§„ μ •λ‹΅ λ°°μ—΄μ˜ λ²”μœ„λ₯Ό λ²—μ–΄λ‚˜λŠ” 경우 (문제 μˆ˜κ°€ 더 λ§Žμ€ 경우) μ ‘κ·Ό index 값을 % 을 μ‚¬μš©ν•΄ λ³€κ²½ν•œλ‹€.

πŸ“„ CODE

μ½”λ“œ 보기/μ ‘κΈ°πŸ’«
import java.util.*; class Solution { public int[] solution(int[] answers) { int[] std1 = {1,2,3,4,5}; int[] std2 = {2,1,2,3,2,4,2,5}; int[] std3 = {3,3,1,1,2,2,4,4,5,5}; int[] scores = new int[3]; scores[0] = countScore(answers, std1); scores[1] = countScore(answers, std2); scores[2] = countScore(answers, std3); int max = Arrays.stream(scores).max().getAsInt(); ArrayList<Integer> answer = new ArrayList<>(); for (int i = 0; i < 3; i++) { if (scores[i] == max) answer.add(i + 1); } return answer.stream().mapToInt(i -> i).toArray(); } private int countScore(int[] answers, int[] std) { int score = 0; for (int i = 0, idx = 0; i < answers.length; i++) { if (idx >= std.length) idx = idx % std.length; if (std[idx++] == answers[i]) score++; } return score; } }

✏️ Review

  • μ™„μ „ 탐색 μ•Œκ³ λ¦¬μ¦˜λ‹΅κ²Œ λ‹¨μˆœνžˆ λ‹€ 돌렀보면 λ˜λŠ” λ¬Έμ œμ˜€λ‹€.

πŸ“• 좜처

Programmers : https://programmers.co.kr/learn/courses/30/lessons/42840

@Seongukbaek
배우고 μ •λ¦¬ν•˜κ³  κ³΅μœ ν•˜λŠ” λŒ€ν•™μƒ λ°±μ„±μš±μž…λ‹ˆλ‹€ πŸ˜€